package penguin.masking;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author wuxh
 * @version 1.0.0
 */
public class MapWordManager extends WordManager {

    Set<String> words = new HashSet<>();
    Map<String, Set<String>> userWords = new HashMap<>();
    long update = 0;
    long updateUserWord = 0;

    @Override
    protected Map<String, SensitiveWordMasking> reloadUserMasking(Map<String, SensitiveWordMasking> userMaskingMap) {
        Map<String, SensitiveWordMasking> _maskingMap = new HashMap<>();
        Set<Map.Entry<String, Set<String>>> entries = userWords.entrySet();
        for (Map.Entry<String, Set<String>> entry : entries) {
            String name = entry.getKey();
            SensitiveWordMasking wordMasking = userMaskingMap.get(name);
            if (wordMasking == null || updateUserWord != wordMasking.getLastModifiedTime()) {
                SensitiveWordMasking masking = new SensitiveWordMasking(entry.getValue());
                masking.setUser(name);
                masking.setLastModifiedTime(updateUserWord);
                _maskingMap.put(masking.getUser(), masking);
            } else {
                _maskingMap.put(wordMasking.getUser(), wordMasking);
            }
        }
        return _maskingMap;
    }

    @Override
    protected SensitiveWordMasking loadDefaultMasking(SensitiveWordMasking defaultMasking) {
        if (defaultMasking == null || update != defaultMasking.getLastModifiedTime()) {
            SensitiveWordMasking masking = new SensitiveWordMasking(words);
            masking.setLastModifiedTime(update);
            return masking;
        }
        return defaultMasking;
    }

    public void setWords(Set<String> words) {
        update = System.currentTimeMillis();
        this.words = words;
    }

    public void setUserWords(Map<String, Set<String>> userWords) {
        updateUserWord = System.currentTimeMillis();
        this.userWords = userWords;
    }
}
